package com.wtf.generator.aop;


import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.wtf.generator.model.dto.DsSqlDTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * description: 数据库类型枚举
 * date: 2022/6/18 10:59
 * @author linhuanyou
 * @email 496558736@qq.com
 * @version 1.0
 */
@Aspect
@Slf4j
@Component
public class DataSourceArgsAdvisor {


    /**
     * 配置切入点表达式
     */
    @Pointcut("execution(* com.wtf.generator.executor.DsDbExecutor.doExecutor(..))")
    public void permissionDataPointCut() {

    }

    /**
     * 配置环绕通知
     *
     * @param point point
     * @return object
     */
    @Around("permissionDataPointCut()")
    public Object permissionHandle(ProceedingJoinPoint point) throws Throwable {
        DsSqlDTO dsSqlDTO = (DsSqlDTO) Arrays.stream(point.getArgs()).filter(e -> {
            return e instanceof DsSqlDTO;
        }).findFirst().get();
        log.info("JdbcTemplate Executor Request : {}",dsSqlDTO);
        String dsKey = dsSqlDTO.getDs();
        DynamicDataSourceContextHolder.push(dsKey);
        Object result;
        try {
            result = point.proceed(point.getArgs());
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
        log.info("JdbcTemplate Executor Result : {}",result);
        return result;
    }
}
